package com.elasicsearch.service;

import com.elasicsearch.pojo.Goods;
import com.elasicsearch.resp.GoodsRepository;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by
 *
 * @author touni
 * @date 2019/4/28
 * @time 11:27
 */
@Service
public class GoodsSearchService {

    @Autowired
    private GoodsRepository goodsRepository;

    @Autowired
    private ElasticsearchTemplate template;


    /**
     * 查询出goods来，导入到索引库中
     * @return
     */
    public ResponseEntity addGoods() {
        //判断是否有索引和映射
        if (!template.indexExists(Goods.class)){
            //如果没有索引则生成索引
            template.createIndex(Goods.class);
        }
        if (null == template.getMapping(Goods.class) ){
            //如果没有创建则生成映射
            template.putMapping(Goods.class);
        }
        //组装goods
        List<Goods> goodsList = new ArrayList<>();
        Goods goods = new Goods();
        // todo ...............  组装goods
        goodsList.add(goods);
        //将商品导入到索引库中
        goodsRepository.saveAll(goodsList);
        return ResponseEntity.status(HttpStatus.ACCEPTED).body("导入成功");
    }


    public ResponseEntity searchGoods(String key) {
        //构建查询条件
        NativeSearchQueryBuilder queryBuilder = new NativeSearchQueryBuilder();
        queryBuilder.withQuery(QueryBuilders.matchQuery("title",key));
        Page<Goods> goodsPage = this.goodsRepository.search(queryBuilder.build());
        long count = goodsPage.getTotalElements();
        System.out.println("总共的查询结果是："+count);
        return ResponseEntity.status(HttpStatus.ACCEPTED).body(goodsPage);
    }























}
